<template>
    <div class="resources-container">
        <!-- 页面标题和搜索栏 -->
        <div class="page-header">
            <div class="header-left">
                <h1 class="page-title">资源中心</h1>
            </div>
            <div class="header-right">
                <div class="search-bar">
                    <el-input v-model="params.name" placeholder="搜索你感兴趣的资源,按回车键搜索..." :prefix-icon="Search"
                        clearable @keyup.enter="handleSearch" />
                </div>
                <el-button type="primary" :icon="UploadFilled"  @click="showUploadDialog">
                    上传资源
                </el-button>
            </div>
        </div>

        <!-- 分类内容 -->
         <div v-for="category in categories" :key="category.id" class="category-section">
            <template v-if="category.resources?.length > 0">
                <div class="category-header">
                    <div class="category-title">
                        <svg-icon :icon-class="category.remark"></svg-icon>
                        <h2>{{ category.label }}</h2>
                    </div>
                </div>

                <div class="resources-grid">
                    <div v-for="resource in category.resources" :key="resource.id" class="resource-card"
                        @click="handleResourceClick(resource)">
                        <div class="resource-content">
                            <div class="resource-icon">
                                <svg-icon :icon-class="category.remark"></svg-icon>
                            </div>
                            <div class="resource-info">
                                <div class="resource-name text-ellipsis" :title="resource.name">{{ resource.name }}
                                </div>
                                <div class="resource-meta">
                                    <el-tag size="mini" :type="!resource.isFree ? 'success' : 'warning'" effect="plain">
                                        {{ !resource.isFree ? '免费' : '付费' }}
                                    </el-tag>
                                </div>
                            </div>
                        </div>
                        <div class="resource-footer">
                            <div class="resource-uploader text-ellipsis">
                                <img :src="resource.avatar" class="uploader-avatar">
                                <span class="uploader-name">{{ resource.nickname }}</span>
                            </div>
                            <div class="resource-stats">
                                <span class="upload-time">
                                    <i class="el-icon-time"></i> {{ formatTime(resource.createTime) }}
                                </span>
                                <span class="download-count" title="下载次数">
                                    <i class="el-icon-download"></i> {{ resource.downloads || 0 }}
                                </span>
                                <span class="view-count" title="浏览次数">
                                    <i class="el-icon-view"></i> {{ resource.views || 0 }}
                                </span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 每个分类的分页 -->
                <div class="pagination-box" v-if="category.total > params.pageSize">
                    <el-pagination v-model:current-page="categoryPages[category.id]" :page-size="params.pageSize"
                        layout="prev, pager, next" :total="category.total"
                        @current-change="(page) => handlePageChange(page, category)" />
                </div>
            </template>
                
            </div>
        


        <!-- 上传组件（v-model 双向绑定） -->
        <Add :visible="uploadDialogVisible" :categories="categories"  @update:visible="uploadDialogVisible = false"/>

        <!-- 资源详情对话框 -->
        <el-dialog title="资源详情" v-model="detailDialogVisible" width="600px" class="resource-detail-dialog"
            top="5vh" :close-on-click-modal="false">
            <div class="resource-detail" v-if="currentResource">
                <div class="detail-header">
                    <div class="resource-icon">
                        <svg-icon :icon-class="currentResource.categoryIcon"></svg-icon>
                    </div>
                    <h3 class="resource-title">{{ currentResource.name }}</h3>
                    <el-tag size="small" :type="!currentResource.isFree ? 'success' : 'warning'" effect="plain">
                        {{ !currentResource.isFree ? '免费' : '付费' }}
                    </el-tag>
                </div>

                <el-descriptions border>
                    <el-descriptions-item label="上传者">
                        <div class="uploader-info text-ellipsis">
                            <img :src="currentResource.avatar" class="uploader-avatar">
                            <span>{{ currentResource.nickname }}</span>
                        </div>
                    </el-descriptions-item>
                    <el-descriptions-item label="上传时间">{{ formatTime(currentResource.createTime)
                    }}</el-descriptions-item>
                    <el-descriptions-item label="下载次数">{{ currentResource.downloads || 0 }}</el-descriptions-item>
                    <el-descriptions-item label="资源描述">{{ currentResource.description || '暂无描述'
                    }}</el-descriptions-item>
                </el-descriptions>

                <!-- 添加获取链接部分 -->
                <div class="get-link-section" v-if="!showVerifyCode">
                    <el-button type="primary" @click="handleGetLink">
                        获取下载链接
                    </el-button>
                    <p class="tip">点击获取链接后需要扫码验证</p>
                </div>

                <!-- 验证码部分 -->
                <div class="verify-section" v-if="showVerifyCode">
                    <div class="qr-code">
                        <img v-lazy="'https://img.shiyit.com/qrcode.jpg'" :key="'https://img.shiyit.com/qrcode.jpg'"
                            alt="扫码获取验证码">
                        <p class="scan-tip">请使用微信扫码关注公众号发送 <span class="code-tip">验证码</span> 获取验证码</p>
                    </div>
                    <el-form :model="verifyForm" class="verify-form">
                        <el-form-item>
                            <el-input v-model="verifyForm.code" placeholder="请输入验证码" maxlength="6">
                                <template #append>
                                    <el-button type="primary" @click="handleVerify" :loading="verifying">
                                        验证
                                    </el-button>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-form>
                </div>

                <!-- 下载链接部分 -->
                <div class="download-link-section" v-if="currentResource.panPath">
                    <div class="link-item">
                        <span class="label">网盘链接:</span>
                        <el-input v-model="currentResource.panPath" readonly>
                            <el-button #append @click="copyText(currentResource.panPath)">
                                复制
                            </el-button>
                        </el-input>
                    </div>
                    <div class="link-item" v-if="currentResource.panCode">
                        <span class="label">提取码:</span>
                        <el-input v-model="currentResource.panCode" readonly>
                            <el-button #append @click="copyText(currentResource.panCode)">
                                复制
                            </el-button>
                        </el-input>
                    </div>
                </div>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleCloseDetail">关闭</el-button>
                </div>
            </template>

        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { storeToRefs } from 'pinia';
import { useAuthStore } from '@/store/index.js';
import { Search,Upload,UploadFilled } from '@element-plus/icons-vue'; 

// 导入组件和API
import Add from './components/add.vue';
import { getDictDataApi } from '@/api/dict';
import { getResourcesApi, verifyCodeApi } from '@/api/resources';
import { formatTime } from '@/utils/time';

// 响应式数据
const categories = ref([]); // 资源分类列表
const uploadDialogVisible = ref(false); // 上传对话框显示状态
const detailDialogVisible = ref(false); // 详情对话框显示状态
const currentResource = ref(null); // 当前选中的资源
const showVerifyCode = ref(false); // 是否显示验证码
const verifying = ref(false); // 验证加载状态
const categoryPages = ref({}); // 每个分类的当前页码（键：分类id，值：页码）

// 请求参数
const params = reactive({
    pageNum: 1,
    pageSize: 8,
    category: '',
    name: ''
});

// 验证码表单
const verifyForm = reactive({
    code: ''
});

// Pinia Store（用户信息）
const authStore = useAuthStore();

// 生命周期：替代created
onMounted(async () => {
    await getCategory();
    // 初始化每个分类的页码
    nextTick(() => {
        categories.value.forEach(category => {
            categoryPages.value[category.id] = 1;
        });
    });
});

// 核心方法

/**
 * 获取资源分类
 */
const getCategory = async () => {
    try {
        const res = await getDictDataApi('sys_resource_category');
        categories.value = res.data || [];
        // 获取分类下的资源
        await getResources();
    } catch (error) {
        ElMessage.error('获取分类失败：' + error.message);
    }
};

/**
 * 获取分类下的资源
 */
const getResources = async () => {
    for (const category of categories.value) {
        params.category = category.value;
        try {
            const res = await getResourcesApi(params);
            // 给分类添加资源列表和总数（Vue 3中直接赋值即可响应式）
            category.resources = res.data.records || [];
            category.total = res.data.total || 0;
        } catch (error) {
            ElMessage.error(`获取${category.label}资源失败：${error.message}`);
        }
    }
};

/**
 * 分页切换
 */
const handlePageChange = async (page, category) => {
    categoryPages.value[category.id] = page; // 更新当前分类的页码
    params.category = category.value;
    params.pageNum = page;
    try {
        const res = await getResourcesApi(params);
        category.resources = res.data.records || [];
        category.total = res.data.total || 0;
    } catch (error) {
        ElMessage.error('分页加载失败：' + error.message);
    }
};

/**
 * 搜索资源
 */
const handleSearch = () => {
    params.pageNum = 1; // 重置页码
    getResources();
};

/**
 * 点击资源卡片，显示详情
 */
const handleResourceClick = (resource) => {
    // 找到资源对应的分类图标
    const category = categories.value.find(c => c.value === resource.category);
    currentResource.value = {
        ...resource,
        categoryIcon: category?.remark || ''
    };
    detailDialogVisible.value = true;
};

/**
 * 显示上传对话框
 */
const showUploadDialog = () => {
    // 未登录时提示
    if (!authStore.userInfo) {
        ElMessage.warning('请先登录');
        return;
    }
    uploadDialogVisible.value = true;
    console.log("add",uploadDialogVisible.value)
};

/**
 * 点击"获取下载链接"
 */
const handleGetLink = () => {
    if (!authStore.userInfo) {
        ElMessage.warning('请先登录');
        return;
    }
    showVerifyCode.value = true;
};

/**
 * 验证验证码
 */
const handleVerify = async () => {
    if (!verifyForm.code) {
        ElMessage.warning('请输入验证码');
        return;
    }
    verifying.value = true;
    try {
        const res = await verifyCodeApi({
            ...verifyForm,
            id: currentResource.value?.id
        });
        // 更新当前资源的下载链接和提取码
        currentResource.value.panPath = res.data.panPath;
        currentResource.value.panCode = res.data.panCode;
        ElMessage.success('验证成功，已获取下载链接');
    } catch (error) {
        ElMessage.error(error.message || '验证失败');
    } finally {
        verifying.value = false;
    }
};

/**
 * 复制文本到剪贴板
 */
const copyText = async (text) => {
    try {
        await navigator.clipboard.writeText(text);
        ElMessage.success('复制成功');
    } catch (error) {
        ElMessage.error('复制失败，请手动复制');
    }
};

/**
 * 关闭详情对话框
 */
const handleCloseDetail = () => {
    detailDialogVisible.value = false;
    showVerifyCode.value = false;
    verifyForm.code = '';
    currentResource.value = null;
};
</script>

<style scoped lang="scss">
$text-color: #2c3e50;

.resources-container {
    padding: 30px;
    max-width: 1200px;
    margin: 0 auto;
    min-height: calc(100vh - 60px);
}

.page-header {
    margin-bottom: 40px;
    text-align: left;
    background: var(--resources-bg);
    padding: 60px;
    border-radius: 24px;
    position: relative;
    overflow: hidden;
    display: grid;
    grid-template-columns: 0.8fr 1.2fr;
    gap: 40px;
    align-items: center;
    box-shadow:
        inset 0 0 60px rgba(64, 158, 255, 0.06),
        0 10px 30px -10px rgba(64, 158, 255, 0.05);

    &::before {
        content: '';
        position: absolute;
        top: -50%;
        left: -50%;
        width: 200%;
        height: 200%;
        background:
            radial-gradient(circle at 20% 30%, rgba(64, 158, 255, 0.08) 0%, transparent 50%),
            radial-gradient(circle at 80% 70%, rgba(83, 82, 237, 0.08) 0%, transparent 50%);
        animation: rotate 60s linear infinite;
    }

    &::after {
        content: '';
        position: absolute;
        inset: 0;
        background:
            linear-gradient(120deg, rgba(255, 255, 255, 0.6) 0%, transparent 50%),
            linear-gradient(-120deg, rgba(255, 255, 255, 0.4) 0%, transparent 50%);
        pointer-events: none;
    }

    .header-left {
        position: relative;
        z-index: 1;
    }

    .header-right {
        display: flex;
        gap: 20px;
        align-items: center;
        position: relative;
        z-index: 1;
        width: 100%;

        .search-bar {
            flex: 1;
        }

        .el-button {
            flex-shrink: 0;
            height: 56px;
            padding: 0 30px;
            font-size: 16px;
            border-radius: 16px;
            transition: all 0.3s ease;

            &:hover {
                transform: translateY(-2px);
            }
        }
    }

    .search-bar {
        max-width: none;
        margin: 0;
        position: relative;
        z-index: 1;
        filter: drop-shadow(0 8px 16px rgba(0, 0, 0, 0.04));

        :deep(.el-input__wrapper){
            border-radius: 16px !important;
        }
        :deep(.el-input__inner) {
            height: 56px;
            border: none !important;
        }

        :deep(.el-input-group__append) {
            background: rgba(255, 255, 255, 0.9);
            backdrop-filter: blur(10px);
            border-color: rgba(64, 158, 255, 0.1);
            padding: 0 20px;
            font-size: 15px;
        }

        :deep(.el-select .el-input__inner) {
            border: none;
            background: transparent;
            height: auto;
            padding: 0;
        }
    }
}

.page-title {
    font-size: 42px;
    line-height: 1.2;
    background: linear-gradient(120deg, #2b5dff 0%, #5352ed 50%, #2b5dff 100%);
    background-size: 200% auto;
    -webkit-background-clip: text;
    background-clip: text;
    -webkit-text-fill-color: transparent;
    margin-bottom: 20px;
    font-weight: 800;
    position: relative;
    z-index: 1;
    letter-spacing: -0.5px;
    text-shadow: 0 2px 15px rgba(83, 82, 237, 0.15);
    animation: shine 8s linear infinite;

    &::after {
        content: '发现优质资源';
        display: block;
        font-size: 16px;
        font-weight: 400;
        color: #666;
        margin-top: 12px;
        background: none;
        -webkit-text-fill-color: initial;
        text-shadow: none;
    }
}

.category-section {
    border-radius: 12px;
    padding: 24px;
    margin-bottom: 24px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
    background: var(--card-bg);

    .category-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;

        .category-title {
            display: flex;
            align-items: center;
            gap: 10px;
            background: linear-gradient(135deg, rgba(64, 158, 255, 0.12), rgba(83, 82, 237, 0.12));
            padding: 12px 20px;
            border-radius: 8px;
            position: relative;
            overflow: hidden;
            border: 1px solid rgba(64, 158, 255, 0.1);

            &::before {
                content: '';
                position: absolute;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background: linear-gradient(45deg, rgba(255, 255, 255, 0.1), transparent);
                pointer-events: none;
            }

            i {
                font-size: 20px;
                color: $primary;
            }

            h2 {
                font-size: 18px;
                font-weight: 600;
                color: var(--text-primary);
                margin: 0;
            }
        }

    }

    .resources-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
        gap: 20px;

        .resource-card {
            background: var(--card-bg);
            border-radius: 8px;
            transition: all 0.3s ease;
            cursor: pointer;
            border: 1px solid var(--border-color);
            display: flex;
            flex-direction: column;
            color: var(--text-primary);

            &:hover {
                transform: translateY(-3px);
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
                border-color: $primary;
            }

            .resource-content {
                padding: 16px;
                flex: 1;
            }

            .resource-icon {
                text-align: center;
                margin-bottom: 12px;

                svg {
                    width: 50px;
                    height: 50px;
                }
            }

            .resource-info {
                text-align: center;

                .resource-name {
                    font-size: 14px;
                    margin-bottom: 8px;
                    font-weight: 500;
                }

                .resource-meta {
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    gap: 8px;
                }
            }

            .resource-footer {
                padding: 12px 16px;
                border-top: 1px solid var(--border-color);
                display: flex;
                justify-content: space-between;
                align-items: center;

                .resource-uploader {
                    display: flex;
                    align-items: center;
                    gap: 6px;
                    max-width: 90px;

                    .uploader-name {
                        font-size: 12px;
                    }
                }

                .resource-stats {
                    display: flex;
                    gap: 12px;
                    font-size: 12px;

                    .download-count,
                    .view-count,
                    .upload-time {
                        display: flex;
                        align-items: center;
                        gap: 4px;
                    }
                }
            }
        }
    }
}

.text-ellipsis {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}


@keyframes shine {
    0% {
        background-position: 0% 50%;
    }

    50% {
        background-position: 100% 50%;
    }

    100% {
        background-position: 0% 50%;
    }
}

@keyframes rotate {
    from {
        transform: rotate(0deg);
    }

    to {
        transform: rotate(360deg);
    }
}

@media (max-width: 1200px) {
    .page-header {
        grid-template-columns: 1fr;
        gap: 30px;
        padding: 40px 30px;
    }
}

@media (max-width: 768px) {
    .page-header {
        padding: 30px 20px;

        .header-right {
            flex-direction: column;
            gap: 15px;

            .el-button {
                width: 100%;
            }
        }
    }

    .page-title {
        font-size: 32px;
    }
}

.resource-detail-dialog {
    :deep(.el-dialog__body) {
        padding: 30px;
    }
}

.resource-detail {
    .detail-header {
        text-align: center;
        margin-bottom: 30px;

        .resource-icon {
            margin-bottom: 15px;

            svg {
                width: 60px;
                height: 60px;
            }
        }

        .resource-title {
            font-size: 20px;
            margin: 0 0 10px;
            color: var(--text-primary);
        }
    }

    .uploader-info {
        display: flex !important;
        align-items: center !important;
        gap: $spacing-base !important;
        max-width: 140px;
    }
}

.get-link-section {
    text-align: center;
    margin-top: 20px;
    padding: 20px;
    border-top: 1px solid var(--border-color);

    .tip {
        margin-top: 10px;
        color: #909399;
        font-size: 12px;
    }
}

.verify-section {
    text-align: center;
    margin-top: 20px;
    padding: 20px;
    border-top: 1px solid var(--border-color);

    .qr-code {
        margin-bottom: 20px;

        img {
            width: 200px;
            height: 200px;
            margin-bottom: 10px;
        }

        .scan-tip {
            color: #909399;
            font-size: 14px;

            .code-tip {
                color: $primary;
            }
        }
    }

    .verify-form {
        max-width: 300px;
        margin: 0 auto;
    }
}

.download-link-section {
    margin-top: 20px;
    padding: 20px;
    border-top: 1px solid var(--border-color);

    .link-item {
        margin-bottom: 15px;

        .label {
            display: block;
            margin-bottom: 5px;
            color: #909399;
        }

        :deep(.el-input-group__append) {
            cursor: pointer;
        }
    }
}

.uploader-avatar {
    width: 20px;
    height: 20px;
    border-radius: 50%;
    object-fit: cover;
}
</style>